package ncs.admin.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import ncs.common.model.RSResult;
import ncs.common.model.exception.UserExistException;
import ncs.admin.database.AdminDAO;
import ncs.admin.model.CRUpdateAdmin;
import ncs.admin.model.Admin;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;

public class AdminAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private String query;
	private InputStream inputStream;
	private RSResult result;
	public String getQuery() {
		return query;
	}
	public void setQuery(String query) {
		this.query = query;
	}
	public InputStream getInputStream() {
		return inputStream;
	}
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public String addAdmin() throws Exception
	{
		System.out.println(query);
		Admin admin=(Admin)JSON.parseObject(query, Admin.class);
		admin.setPassword(admin.getUserID());
		AdminDAO dao=new AdminDAO();
		result=new RSResult();
		result.setCode(0);
		try {
			dao.addAdmin(admin);
		} catch (UserExistException e) {
			result.setCode(1);
			result.setMsg("用户已存在");
			
		} catch (Exception ex) {
			result.setCode(2);
			result.setMsg("系统繁忙，请稍后再试");
		}
		String json=JSON.toJSONString(result);
		inputStream=new ByteArrayInputStream(json.getBytes("UTF-8"));
		return SUCCESS;
	}

	public String updateAdmin() throws Exception {
		CRUpdateAdmin packet = JSON.parseObject(query, CRUpdateAdmin.class);
		AdminDAO dao = new AdminDAO();
		result=new RSResult();
		result.setCode(0);
		try {
			dao.updateAdminField(packet.getId(), packet.getField(),packet.getValue());
		} catch (UserExistException e) {
			result.setCode(1);
			result.setMsg("更新失败,该用户已存在");

		} catch (Exception ex) {
			result.setCode(2);
			result.setMsg("系统繁忙，请稍后再试");
		}
		String json=JSON.toJSONString(result);
		inputStream=new ByteArrayInputStream(json.getBytes("UTF-8"));
		return SUCCESS;
	}
	public String deleteAdmin() throws Exception{
		int[]id=JSON.parseObject(query,int[].class);
		AdminDAO dao=new AdminDAO();
		result=new RSResult();
		result.setCode(0);
		try
		{
			dao.deleteAdmin(id);
		}catch(Exception ex)
		{
			result.setCode(1);
			result.setMsg("数据错误");
		}
		String json=JSON.toJSONString(result);
		inputStream=new ByteArrayInputStream(json.getBytes("UTF-8"));
		return SUCCESS;
	}

}
